<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="省市区编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入省市区编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上级编号" prop="parentCode">
        <el-input
          v-model="queryParams.parentCode"
          placeholder="请输入上级编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入区名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区域等级" prop="level">
        <el-input
          v-model="queryParams.level"
          placeholder="请输入区域等级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['logistics:region:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="regionList"
      row-key="code"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="省市区编号" prop="code" />
      <el-table-column label="上级编号" align="center" prop="parentCode" />
      <el-table-column label="区名" align="center" prop="name" />
      <el-table-column label="区域等级" align="center" prop="level" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['logistics:region:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['logistics:region:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['logistics:region:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

<!--    <template>
      <div>
        <div @click="showPopup($event)">点击我弹出弹窗</div>
        <el-dialog
          :visible.syn="popupVisible"
          :top="popupY + 'px'"
          :left="popupX + 'px'"
        >
          <div style="width: 50px ; height: 50px ; background-color: green">123</div>
          &lt;!&ndash; 弹窗内容 &ndash;&gt;
        </el-dialog>
      </div>
    </template>-->


    <!-- 添加或修改详细地区对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="740px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="省市区编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入省市区编号" />
        </el-form-item>
        <el-form-item label="上级编号" prop="parentCode">
          <treeselect v-model="form.parentCode" :options="regionOptions" :normalizer="normalizer" placeholder="请选择上级编号" />
        </el-form-item>
        <el-form-item label="区名" prop="name">
          <el-input v-model="form.name" placeholder="请输入区名" />
        </el-form-item>
        <el-form-item label="区域等级" prop="level">
          <el-input v-model="form.level" placeholder="请输入区域等级" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <div v-if="form.level===2 || form.code===110000 || form.code===120000 || form.code===310000 || form.code===500000">
          <el-divider content-position="center">物流中心信息</el-divider>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddCenter">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteCenter">删除</el-button>
            </el-col>
          </el-row>
          <el-table :data="centerList" :row-class-name="rowCenterIndex" @selection-change="handleCenterSelectionChange"
                    ref="center">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column label="物流中心名称" prop="name" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.name" placeholder="请输入物流中心名称"/>
              </template>
            </el-table-column>
            <el-table-column label="类型" prop="type" width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.type" placeholder="请选择类型">
                  <el-option
                    v-for="dict in dict.type.log_center_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="纬度" prop="longitude" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.longitude" placeholder="请输入纬度"/>
              </template>
            </el-table-column>
            <el-table-column label="经度" prop="latitude" width="150">
              <template slot-scope="scope">
                <el-input v-model="scope.row.latitude" placeholder="请输入经度"/>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRegion,
  getRegion,
  delRegion,
  addRegion,
  updateRegion,
  listRegionCenter,
  getExplicitRegion
} from "@/api/logistics/region";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Region",
  dicts: ['log_center_type'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 详细地区表格数据
      regionList: [],
      // 详细地区树选项
      regionOptions: [],
      // 物流中心表格数据
      centerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        code: null,
        parentCode: null,
        name: null,
        level: null,
        longitude: null,
        latitude: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "省市区编号不能为空", trigger: "blur" }
        ],
        parentCode: [
          { required: true, message: "上级编号不能为空", trigger: "blur" }
        ],
      },
      popupVisible: false, // 弹窗显示状态
      popupX: 0, // 弹窗的横坐标
      popupY: 0 // 弹窗的纵坐标
    };
  },
  created() {
    /*listRegionCenter(3).then(response => {
      this.menus=response.data
      console.log(this.menus)
    })*/
    this.getList();
  },
  methods: {
    showPopup(event) {
      console.log(1)
      this.popupVisible = true;
      this.popupX = event.clientX;
      this.popupY = event.clientY;
    },

    /** 查询详细地区列表 */
    getList() {
      this.loading = true;

      listRegion(this.queryParams).then(response => {
        console.log("response.data")
        console.log(response.data)
        this.regionList = this.handleTree(response.data, "code", "parentCode");
        console.log("this.regionList")
        console.log(this.regionList)
        this.loading = false;
      });
    },
    /** 转换详细地区数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.code,
        label: node.name,
        children: node.children
      };
    },
	/** 查询详细地区下拉树结构 */
    getTreeselect() {
      listRegion().then(response => {
        this.regionOptions = [];
        const data = { code: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "code", "parentCode");
        this.regionOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        parentCode: null,
        name: null,
        level: null,
        longitude: null,
        latitude: null,
      };
      this.centerList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.code) {
        this.form.parentCode = row.code;
      } else {
        this.form.parentCode = 0;
      }
      this.open = true;
      this.title = "添加详细地区";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentCode = row.code;
      }
      getExplicitRegion(row.id).then(response => {
        this.form = response.data;
        this.centerList = response.data.centerList;
        console.log("this.centerList")
        console.log(this.centerList)
        this.open = true;
        this.title = "修改详细地区";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRegion(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRegion(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除详细地区编号为"' + row.id + '"的数据项？').then(function() {
        return delRegion(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 物流中心序号 */
    rowCenterIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 物流中心添加按钮操作 */
    handleAddCenter() {
      let obj = {};
      obj.name = "";
      obj.type = "";
      obj.longitude = "";
      obj.latitude = "";
      this.centerList.push(obj);
    },
    /** 物流中心删除按钮操作 */
    handleDeleteCenter() {
      if (this.checkedCenter.length == 0) {
        this.$modal.msgError("请先选择要删除的物流中心数据");
      } else {
        const centerList = this.centerList;
        const checkedCenter = this.checkedCenter;
        this.centerList = centerList.filter(function (item) {
          return checkedCenter.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleCenterSelectionChange(selection) {
      this.checkedCenter = selection.map(item => item.index)
    },
  }
};
</script>
